package com.example.mideaoem.api;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.example.mideaoem.api.handler.IDateZoomTransformer;
import com.example.mideaoem.api.handler.SecurityHandle;
import com.example.mideaoem.bean.BaseMessage;
import com.example.mideaoem.model.AcCheckItemDetails;
import com.example.mideaoem.model.AppInfo;
import com.example.mideaoem.model.ApplianceInfo;
import com.example.mideaoem.model.CheckDetails;
import com.example.mideaoem.model.CurveSleep;
import com.example.mideaoem.model.DeviceAppoint;
import com.example.mideaoem.model.Elec;
import com.example.mideaoem.model.Family;
import com.example.mideaoem.model.FamilyInfo;
import com.example.mideaoem.model.MessageInfo;
import com.example.mideaoem.model.QueryElecCell;
import com.example.mideaoem.model.User;
import com.example.mideaoem.model.UserInfo;
import com.example.mideaoem.model.VersionInfo;
import com.example.mideaoem.utils.DateUtil;

public class JsonParser {
	
	private int PC = 0;
	private int ANDROID = 1;
	private int IOS = 2;
	
	private int OKCode = 0;
	
	private String CODE = "errorCode";
	private String MSG = "msg";

	private static JsonParser instance;
	public static JsonParser getInstance(){
		if(instance == null){
			instance = new JsonParser();
		}
		return instance;
	}
	private JsonParser() {
	}
	
	
	public String TestPostRequest(String userName, String password) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("phone_number", userName);
			json.put("password", password);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}

	
	public int TestPostResponse(String json) {
		// TODO Auto-generated method stub
		int success = -1;
		try {
			JSONObject jsonObj = new JSONObject(json);
			int code = jsonObj.getInt("code");
			if(code == 0){
				success = 0;
			}else{
				success = code;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return success;
	}
	

	public BaseMessage IsSuccess(String json){
		BaseMessage base = new BaseMessage();
		try{
			JSONObject jsonObj = new JSONObject(json);
			try{
				base.setCode(Integer.valueOf(jsonObj.getInt(CODE)));
			}catch(JSONException E){
				base.setCode(Integer.valueOf(jsonObj.getInt("errCode")));
				E.printStackTrace();
			}
			if(base.getCode() != 0){
				try{
					base.setMessage(jsonObj.getString(MSG));
				}catch(JSONException E){
					base.setMessage(jsonObj.getString("errMsg"));
					E.printStackTrace();
				}
			}else{
				base.setMessage("success!");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return base;
	}
	
	
	
	
	/****BEGIN*****/
	
	private int appId = 1005;
	private int src = 5;
	private int format = 2;
	
	/**
	 * 判断邮箱是否已注册
	 * @param emalAddr
	 * @return
	 */
	public String CheckEmailAvailableRequest(String emailAddr) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("appId", appId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("email", emailAddr);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public int CheckEmailAvailableResponse(String json){
		int status = 0;
		try{
			JSONObject jsonObj = new JSONObject(json);
			JSONObject result = jsonObj.getJSONObject("result");
			status = Integer.valueOf(result.getString("emailStatus"));
		}catch(Exception e){
			e.printStackTrace();
		}
		return status;
	}
	
	/**
	 * 用户通过邮箱注册
	 * @param emailAddr
	 * @param password
	 * @return
	 */
	public String UserRegisterRequest(String emailAddr, String password){
		JSONObject json = new JSONObject();
		try {
			json.put("appId", appId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("email", emailAddr);
			json.put("password", password);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	
	}
	
	/**
	 * 获取登陆ID
	 * @param emailAddr
	 * @return
	 */
	public String getLoginIDRequest(String emailAddr){
		JSONObject json = new JSONObject();
		try {
			json.put("appId", appId);
			json.put("clientType", 1);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("loginAccount", emailAddr);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	
	}
	
	public String getLoginIdResponse(String json){
		String loginId = "";
		try{
			JSONObject jsonObj = new JSONObject(json);
			JSONObject result = jsonObj.getJSONObject("result");
			loginId = result.getString("loginId");
		}catch(Exception e){
			e.printStackTrace();
		}
		return loginId;
	}

	
	/**
	 * 用户登录
	 * @param email
	 * @return
	 */
	public String userLoginRequest(String emailAddr, String password){
		JSONObject json = new JSONObject();
		try {
			json.put("appId", appId);
			json.put("clientType", 1);
			json.put("src", src);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("loginAccount", emailAddr);
			json.put("password", password);
//			json.put("password", SecurityUtils.encrypt(password, String.valueOf(appId)));
//			json.put("pushToken", "");
			json.put("language", "zh_CN");
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	
	}
	
	public User userLoginResponse(String json){
		User user = new User();
		try{
			JSONObject jsonObj = new JSONObject(json);
			user.setCode(Integer.valueOf(jsonObj.getString(CODE)));
			if (user.getCode() == 0) {
				JSONObject result = jsonObj.getJSONObject("result");
				user.setSessionId(result.getString("sessionId"));
				user.setUserId(result.getString("userId"));
				user.setNickname(result.getString("nickname"));
				user.setAccessToken(result.getString("accessToken"));
			}else{
				user.setMessage(jsonObj.getString(MSG));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return user;
	}
	
	/**
	 * 用户登出
	 * @param sessionId
	 * @return
	 */
	public String userLogoutRequest(String sessionId){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	/**
	 * 获取用户详细信息
	 * @param sessionId
	 * @return
	 */
	public String getUserInfoRequest(String sessionId){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public UserInfo getUserInfoResponse(String json){
		UserInfo userInfo = new UserInfo();
		try{
			JSONObject jsonObj = new JSONObject(json);
			
			JSONObject result = jsonObj.getJSONObject("result");
			userInfo.setId(result.getString("id"));
			userInfo.setNickName(result.getString("nickname"));
			userInfo.setMobile(result.getString("mobile"));
			userInfo.setSex(result.getString("sex"));
			userInfo.setAge(result.getString("age"));
			userInfo.setAddress(result.getString("address"));
			userInfo.setPhone(result.getString("phone"));
			userInfo.setRegisterTime(result.getString("registerTime"));
			userInfo.setProfilePicUrl(result.getString("profilePicUrl"));
		}catch(Exception e){
			e.printStackTrace();
		}
		return userInfo;
	}
	
	/**
	 * 修改密码
	 * @param sessionId
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	public String modifyPassword(String sessionId, String oldPassword, String newPassword){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("oldPassword", oldPassword);
			json.put("newPassword", newPassword);
//			json.put("oldPassword", SecurityUtils.encrypt(oldPassword, String.valueOf(appId)));
//			json.put("newPassword", SecurityUtils.encrypt(newPassword, String.valueOf(appId)));
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	/**
	 * 重置密码
	 * @param emailAddr
	 * @return
	 */
	public String resetPassword(String emailAddr){
		JSONObject json = new JSONObject();
		try {
			json.put("appId", appId);
			json.put("src", src);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("loginAccount", emailAddr);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	/**
	 * 获取家庭列表
	 * @param sessionId
	 * @return
	 */
	public String getHomeListRequest(String sessionId){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	
	
	
	public List<FamilyInfo> getHomeListResponse(String json){
		List<FamilyInfo> FamilyList = new ArrayList<FamilyInfo>();

		try{
			JSONObject jsonObj = new JSONObject(json);
			JSONObject result = jsonObj.getJSONObject("result");
			JSONArray homelist = result.getJSONArray("list");
			
			for(int i=0;i<homelist.length();i++){
				FamilyInfo family = new FamilyInfo();
				family.setId(homelist.getJSONObject(i).getString("id"));
				family.setNumber(homelist.getJSONObject(i).getString("number"));
				family.setRoleId(homelist.getJSONObject(i).getString("roleId"));
				family.setIsDefault(homelist.getJSONObject(i).getString("isDefault"));
				family.setName(homelist.getJSONObject(i).getString("name"));
				family.setNickname(homelist.getJSONObject(i).getString("nickname"));
				family.setDes(homelist.getJSONObject(i).getString("des"));
				family.setAddress(homelist.getJSONObject(i).getString("address"));
				family.setCoordinate(homelist.getJSONObject(i).getString("coordinate"));
				family.setCreateTime(homelist.getJSONObject(i).getString("createTime"));
				FamilyList.add(family);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return FamilyList;
	
	}
	
	/**
	 * 创建家庭
	 * @param sessionId
	 * @param name
	 * @param des
	 * @param address
	 * @param coordinate
	 * @return
	 */
	public String createFamilyRequest(String sessionId, String name, String des, String address, String coordinate){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("name", name);
			json.put("des", des);
			json.put("address", address);
			json.put("coordinate", coordinate);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}

	public Family createFamilyResponse(String json){
		Family family = new Family();
		try{
			JSONObject jsonObj = new JSONObject(json);
			
			JSONObject result = jsonObj.getJSONObject("result");
			family.setId(result.getString("id"));
			family.setNumber(result.getString("number"));
		}catch(Exception e){
			e.printStackTrace();
		}
		return family;
	}
	
	/**
	 * 注销家庭
	 * @param homegroupId
	 * @return
	 */
	public String deleteHome(String sessionId, String homegroupId){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("jomegroupId", homegroupId);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	/**
	 * 获取家庭下的设备列表
	 * @param sessionId
	 * @param homegroupId
	 * @return
	 */
	public String getApplianceListRequest(String sessionId, String homegroupId){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("homegroupId", homegroupId);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	
	public List<ApplianceInfo> getApplianceListResponse(SecurityHandle builder, String json, String accessToken){
		List<ApplianceInfo> ApplianceList = new ArrayList<ApplianceInfo>();

		try{
			JSONObject jsonObj = new JSONObject(json);
			JSONObject result = jsonObj.getJSONObject("result");
			JSONArray applianceslist = result.getJSONArray("list");
			
			for(int i=0;i<applianceslist.length();i++){
				ApplianceInfo applianceInfo = new ApplianceInfo();
				applianceInfo.setApplianceId(applianceslist.getJSONObject(i).getString("id"));
				applianceInfo.setApplianceSN(builder.Decrypt(applianceslist.getJSONObject(i).getString("sn"), BaseAPI.appKey, accessToken).substring(6, 28));
				applianceInfo.setOnlineStatus(applianceslist.getJSONObject(i).getString("onlineStatus").equals("1") ? true : false);
				applianceInfo.setApplianceType(applianceslist.getJSONObject(i).getString("type"));
				applianceInfo.setName(applianceslist.getJSONObject(i).getString("name"));
				applianceInfo.setDes(applianceslist.getJSONObject(i).getString("des"));
				applianceInfo.setActiveStatus(applianceslist.getJSONObject(i).getString("activeStatus").equals("1") ? true : false);
				ApplianceList.add(applianceInfo);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return ApplianceList;
	
	}
	
	/**
	 * 激活家电
	 * @param sessionId
	 * @param applianceSn
	 * @param referSn
	 * @param homegroupId
	 * @param applianceName
	 * @param applianceType
	 * @return
	 */
	public String activeApplianceRequest(String sessionId, String applianceSn, String referSn, String homegroupId, String applianceName, String applianceType){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("applianceSn", applianceSn);
			json.put("referSn", referSn);
//			json.put("applianceSn", SecurityUtils.encrypt(applianceSn, String.valueOf(appId)));
//			json.put("referSn", SecurityUtils.encrypt(referSn, String.valueOf(appId)));
			json.put("homegroupId", homegroupId);
			json.put("applianceName", applianceName);
			json.put("applianceTyte", applianceType);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	/**
	 * 返回家电ID
	 */

	public String activeApplianceResponse(String json){
		String applianceId = "";
		try{
			JSONObject jsonObj = new JSONObject(json);
			JSONObject result = jsonObj.getJSONObject("result");
			applianceId = result.getString("Id");
		}catch(Exception e){
			e.printStackTrace();
		}
		return applianceId;
	}
	
	/**
	 * 删除家电
	 * @param sessionId
	 * @param applianceId
	 * @return
	 */
	public String deleteApplianceRequest(String sessionId, String applianceId){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("applianceId", Long.parseLong(applianceId));
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	/**
	 * 家电透传
	 * @param applianceId
	 * @param funId
	 * @param order
	 * @return
	 */
	public String applianceSendRequest(String sessionId, String applianceId, String funId, String order){
		JSONObject json = new JSONObject();
		try {
			json.put("src", src);
			json.put("sessionId", sessionId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("applianceId", Long.parseLong(applianceId));
			json.put("funId", funId);
			json.put("order", order);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public MessageInfo applianceSendResponse(String json){
		MessageInfo info = new MessageInfo();
		String reply = "";
		try{
			JSONObject jsonObj = new JSONObject(json);
			try{
				info.setErrCode(jsonObj.getString("errorCode"));
				info.setMsg(jsonObj.getString("msg"));
			}catch(Exception e){
				e.printStackTrace();
			}
			JSONObject result = jsonObj.getJSONObject("result");
			reply = result.getString("reply");
		}catch(Exception e){
			e.printStackTrace();
		}
		info.setBeanInfo(reply);
		return info;
	}
	
	//*********//升级类
	public String checkUpdate(String appType){

		JSONObject json = new JSONObject();
		try {
			json.put("appId", appId);
			json.put("src", src);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("clientType", ANDROID);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public List<VersionInfo> checkUpdateResponse(String json){
		List<VersionInfo> infoList = new ArrayList<VersionInfo>();
		try{
			JSONObject jsonObj = new JSONObject(json);
			JSONArray list = jsonObj.getJSONArray("list");
			for(int i=0;i<list.length();i++){
				VersionInfo info = new VersionInfo();
				info.setVersionCode(list.getJSONObject(i).getString("versionCode"));
				info.setAppType(list.getJSONObject(i).getString("appType"));
				infoList.add(info);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return infoList;
	}
	
	/**
	 * 获取升级包信息 
	 * @param appType
	 * @param versionCode
	 * @return
	 */
	public String getAppInfo(String appType, String versionCode){

		JSONObject json = new JSONObject();
		try {
			json.put("appId", appId);
			json.put("format", format);
			json.put("stamp", DateUtil.getTimeStamp());
			json.put("clientType", ANDROID);
			json.put("appType", appType);
			json.put("versionCode", versionCode);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	
	
//	public AppInfo getAppInfoResponse(String json){
//		AppInfo info = new AppInfo();
//		try{
//		JSONObject jsonobj = new JSONObject(json);
//		JSONObject result = 
//		info.setCode(code);
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//	}
	
	
	
	private MessageInfo DefaultResponse(String json){
		MessageInfo info = new MessageInfo();
		try{
			JSONObject jsonObject = new JSONObject(json);
			info.setErrCode(jsonObject.getString("errCode"));
			info.setMsg(jsonObject.getString("errMsg"));
		}catch(Exception e){
			e.printStackTrace();
		}
		return info;
	}
	
	private String createDefaultString(String applianceId){
		JSONObject json = new JSONObject();
		try{
			json.put("applianceId", Long.parseLong(applianceId));
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	/*****    电量统计    *****/
	/**
	 * 2.2.7.1电量统计
	 * 
type：1表示获取某周每天电量，2表示获取某月每天电量，3表示获取某年每月电量，默认为2
某周返回数据key的取值范围为：1-7，周一到周日
某月返回数据key的取值范围为：1-31，1号到31号
某年返回数据key的取值范围为：1-12，1月到12月
totalValue：周、月、年总用电量
totalHour：周、月、年总开机时间
elecDetails：具体统计数据
date：当前日期，格式如”2014-10-09”

	 * 
	 * @param userId
	 * @param applianceId
	 * @param type
	 * @param date
	 * @return
	 */
	public String queryElecRequest(String applianceId, int type,
			String date) {
		JSONObject json = new JSONObject();
		try {
			json.put("applianceId", Long.parseLong(applianceId));
			json.put("type", type);
			json.put("date", date);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public MessageInfo queryElecResponse(String jsonStr, int totalDay) {
		MessageInfo info = new MessageInfo();
		Elec elec = new Elec();
		try {
			JSONObject object = new JSONObject(jsonStr);
			int errCode = object.getInt("errCode");
			String errMsg = object.getString("errMsg");

			if (errCode == 0) {
				
				try{
				JSONObject ElecObject = object.getJSONObject("result");
				elec.setTotalValue(ElecObject.getDouble("totalValue"));
				elec.setTotalHour(ElecObject.getDouble("totalHour"));
				
				JSONArray details = ElecObject.getJSONArray("elecDetails");
				
					int j=0;
					for (int i = 0; i < totalDay; i++) {
						QueryElecCell cell = new QueryElecCell();
						cell.setDateKey(i);
						if (j < details.length()) {
							JSONObject detailObj = details.getJSONObject(j);
							try {
								cell.setElecValue(Double.valueOf(detailObj
										.getString(String.valueOf(i + 1))));
								j++;
							} catch (Exception e) {
								cell.setElecValue(0);
							}
						} else {
							cell.setElecValue(0);
						}
						elec.getCells().add(cell);
					}
				
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
			info.setErrCode(String.valueOf(errCode));
			info.setMsg(errMsg);
			info.setBeanInfo(elec);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return info;

	}
	
	
	/********    睡眠曲线    ********/
	/**
	 * 2.2.9.1 获取睡眠曲线状态
	 * @param userId
	 * @param familyId
	 * @param applianceId
	 * @return
	 */
	
	private int SleepingMode = 2;
	public String getSleepCurveStatusRequest(String applianceId, int mode){
		SleepingMode = mode;
		JSONObject json = new JSONObject();
		try{
			json.put("applianceId", Long.parseLong(applianceId));
			json.put("mode", mode);
		}catch(JSONException e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	
	public MessageInfo getSleepCurveStatusResponse(String json){
		MessageInfo info = new MessageInfo();
		
		try {
			JSONObject object = new JSONObject(json);
			int errCode = object.getInt("errCode");
			String errMsg = object.getString("errMsg");
			
			if (errCode == 0) {
				JSONArray curveArray = object.getJSONArray("result");
				CurveSleep[] curveSleep = new CurveSleep[curveArray.length()];
				for (int i = 0; i < curveArray.length(); i++) {
					CurveSleep curve = new CurveSleep();
					JSONObject curveObject = curveArray.getJSONObject(i);
					curve.setCurveStatus(curveObject.getString("status"));
					curve.setCurveType(curveObject.getString("type"));
					curve.setValue0(curveObject.getInt("value0"));
					curve.setValue1(curveObject.getInt("value1"));
					curve.setValue2(curveObject.getInt("value2"));
					curve.setValue3(curveObject.getInt("value3"));
					curve.setValue4(curveObject.getInt("value4"));
					curve.setValue5(curveObject.getInt("value5"));
					curve.setValue6(curveObject.getInt("value6"));
					curve.setValue7(curveObject.getInt("value7"));
					if (curveObject.toString().contains("value8")) {
						curve.setValue8(curveObject.getInt("value8"));
					} else {
						curve.setValue8(0);
					}
					if (curveObject.toString().contains("value9")) {
						curve.setValue9(curveObject.getInt("value9"));
					} else {
						curve.setValue9(0);
					}
					curveSleep[i] = curve;
				}
				info.setBeanInfo(curveSleep);
			}
			info.setErrCode(String.valueOf(errCode));
			info.setMsg(errMsg);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return info;
		
	}
	
	
	
	/**
	 * 2.2.9.2 开启舒睡曲线
	 * @param userId
	 * @param familyId
	 * @param applianceId
	 * @param curve_sleep
	 * @return
	 */
	public String StartSleepCurveRequest(String applianceId, CurveSleep curve_sleep){
		JSONObject json = new JSONObject();
		try {
			json.put("applianceId", Long.parseLong(applianceId));
			json.put("type", curve_sleep.getCurveType());
			json.put("mode", curve_sleep.getCurveMode());
			json.put("value0", curve_sleep.getValue0());
			json.put("value1", curve_sleep.getValue1());
			json.put("value2", curve_sleep.getValue2());
			json.put("value3", curve_sleep.getValue3());
			json.put("value4", curve_sleep.getValue4());
			json.put("value5", curve_sleep.getValue5());
			json.put("value6", curve_sleep.getValue6());
			json.put("value7", curve_sleep.getValue7());
			json.put("value8", curve_sleep.getValue8());
			json.put("value9", curve_sleep.getValue9());

		}catch(JSONException e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public MessageInfo StartSleepCurveResponse(String json){
		return DefaultResponse(json);
	}
	
	
	
	/**
	 * 2.2.9.3 重新启动舒睡曲线
	 * @param userId
	 * @param familyId
	 * @param applianceId
	 * @param curve_sleep
	 * @return
	 */
	public String RestartSleepCurveRequest(int applianceId, CurveSleep curve_sleep){
		JSONObject json = new JSONObject();
		try {
			json.put("applianceId", applianceId);
			if(curve_sleep.getCurveType() == 0){
				curve_sleep.setCurveType("1");
			}
			json.put("type", curve_sleep.getCurveType());
			json.put("value0", curve_sleep.getValue0());
			json.put("value1", curve_sleep.getValue1());
			json.put("value2", curve_sleep.getValue2());
			json.put("value3", curve_sleep.getValue3());
			json.put("value4", curve_sleep.getValue4());
			json.put("value5", curve_sleep.getValue5());
			json.put("value6", curve_sleep.getValue6());
			json.put("value7", curve_sleep.getValue7());

		}catch(JSONException e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public MessageInfo RestartSleepCurveResponse(String json){
		return DefaultResponse(json);
	}
	
	
	
	/**
	 * 2.2.9.4 关闭舒睡功能
	 * @param userId
	 * @param familyId
	 * @param applianceId
	 * @return
	 */
	public String CloseSleepCurveRequest(String applianceId){
		JSONObject json = new JSONObject();
		try{
			json.put("applianceId", Long.parseLong(applianceId));
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public MessageInfo CloseSleepCurveResponse(String json){
		return DefaultResponse(json);
	}
	
	
	
	/**
	 * 2.2.9.5 修改自定义曲线
	 * @param userId
	 * @param familyId
	 * @param applianceId
	 * @param curve_sleep
	 * @return
	 */
	public String UpdateSleepCurveRequest(String applianceId, CurveSleep curve_sleep){
		JSONObject json = new JSONObject();
		try{
			json.put("applianceId", Long.parseLong(applianceId));
			json.put("type", curve_sleep.getCurveType());
			json.put("mode", SleepingMode);
			json.put("value0", curve_sleep.getValue0());
			json.put("value1", curve_sleep.getValue1());
			json.put("value2", curve_sleep.getValue2());
			json.put("value3", curve_sleep.getValue3());
			json.put("value4", curve_sleep.getValue4());
			json.put("value5", curve_sleep.getValue5());
			json.put("value6", curve_sleep.getValue6());
			json.put("value7", curve_sleep.getValue7());
			json.put("value8", curve_sleep.getValue8());
			json.put("value9", curve_sleep.getValue9());
			json.put("isStart", true);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public MessageInfo UpdateSleepCurveResponse(String json){
		return DefaultResponse(json);
	}
	
	
	
	
	/********    体检     *********/
	/**
	 * 2.2.11.2 开始体检
	 * @param userId
	 * @param familyId
	 * @param applianceId
	 * @return
	 */
	public String StartACCheckRequest(String applianceId){
		return createDefaultString(applianceId);
	}
	
	public MessageInfo StartACCheckResponse(String json){
		MessageInfo info = new MessageInfo();
		String errCode = "0";
		String errMsg = "";
		try {
			JSONObject object = new JSONObject(json);
			try{
				errCode = object.getString("errCode");
			}catch(Exception e){
				errCode = object.getString("errorCode");
			}
			try{
				errMsg = object.getString("errMsg");
			}catch (Exception e){
				e.printStackTrace();
				errMsg = object.getString("msg");
			}

			CheckDetails checkDetails = new CheckDetails();
			if (errCode.equals(OKCode+"")) {
				JSONObject checkedObject = object.getJSONObject("result");
//				checkDetails.setLastCheckTime(checkedObject.getString("checkTime"));
				checkDetails.setCheckNum(checkedObject.getInt("checkNum"));
				checkDetails.setNormNum(checkedObject.getInt("normNum"));
				checkDetails.setSeriousFault(checkedObject.getInt("seriousFault"));
				checkDetails.setGeneralFailure(checkedObject.getInt("generalFailure"));
				checkDetails.setMinorFault(checkedObject.getInt("minorFault"));
				checkDetails.setProposeDes(checkedObject.getString("proposeDes"));
				checkDetails.setProposeAction(checkedObject.getInt("proposeAction"));
			}
			info.setBeanInfo(checkDetails);
			info.setErrCode(errCode);
			info.setMsg(errMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return info;
	}
	
	
	/**
	 * 2.2.11.3 获取体检详情
	 * @param userId
	 * @param familyId
	 * @param applianceId
	 * @return
	 */
	public String AcCheckDetailsRequest(String applianceId){
		return createDefaultString(applianceId);
	}
	
	
	
	public MessageInfo AcCheckDetailsResponse(String json){
		MessageInfo info = new MessageInfo();

		try {
			JSONObject object = new JSONObject(json);
			String errCode = object.getString("errCode");
			String errMsg = object.getString("errMsg");
			
			if (errCode.equals("0")) {
				JSONArray checkArrays = object.getJSONArray("result");
				
				AcCheckItemDetails[] itemDetailsArray = new AcCheckItemDetails[checkArrays.length()];
				
				for(int i=0;i<checkArrays.length();i++){
					
					JSONObject checkedObject = checkArrays.getJSONObject(i);
					AcCheckItemDetails itemDetails = new AcCheckItemDetails();
					itemDetails.setParameterName(checkedObject.getString("parameterName"));
					itemDetails.setRealValue(checkedObject.getInt("realValue"));
					itemDetails.setMinValue(checkedObject.getInt("minValue"));
					itemDetails.setMaxValue(checkedObject.getInt("maxValue"));
					itemDetails.setStatus(checkedObject.getInt("status"));
					itemDetailsArray[i] = itemDetails;
				}
				
				info.setBeanInfo(itemDetailsArray);
			}
			info.setErrCode(errCode);
			info.setMsg(errMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return info;
	}
	
	
	/**
	 * 2.2.14.1 获取产品基础信息
	 * @param applianceId
	 * @param type
	 * @return
	 */
	public String GetApplianceInfoRequest(long applianceId, int type){
		JSONObject json = new JSONObject();
		try{
			json.put("applianceId", applianceId);
			json.put("type", type);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json.toString();
	}
	
	public MessageInfo GetApplianceInfoResponse(String json){
		MessageInfo info = new MessageInfo();

		try {
			JSONObject object = new JSONObject(json);
			String errCode = object.getString("errCode");
			String errMsg = object.getString("errMsg");
			
			if (errCode.equals(OKCode)) {
				JSONObject mApplianceInfo = object.getJSONObject("result");
				ApplianceInfo Ainfo = new ApplianceInfo();
				Ainfo.setName(mApplianceInfo.getString("applianceName"));
				Ainfo.setApplianceSN(mApplianceInfo.getString("applianceSN").substring(6, 28));
				info.setBeanInfo(Ainfo);
			}
			info.setErrCode(errCode);
			info.setMsg(errMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return info;
	}
	
	
	
	
	public MessageInfo getErrCodeInfo(String jsonString){
		MessageInfo info = new MessageInfo();
		String errCode = null;
		String errMsg = null;
		try{
			//获取json对象
			JSONObject jsonObj=new JSONObject(jsonString);
			errCode=jsonObj.getString("errCode");
			errMsg = jsonObj.getString("errMsg");
			}catch(JSONException e){
				e.printStackTrace();
			}
		
		info.setErrCode(errCode);
		info.setMsg(errMsg);
		
		return info;
	}
	
	
	
	/*******     预约     ********/
	
	/**
	 * 1.2.6.1 添加预约
	 * @param userId
	 * @param deviceYuYue
	 * @return
	 */
	public String addApplianceAppointRequest(DeviceAppoint deviceAppoint, IDateZoomTransformer transformer){
		JSONObject jsonObject=new JSONObject();
		
		try{
			jsonObject.put("applianceId", Long.parseLong(deviceAppoint.getApplianceId()));
			jsonObject.put("switcher",deviceAppoint.isSwitcher() ? 2:1);
			jsonObject.put("time", transformer.toUTC(deviceAppoint.getTime()));
//			jsonObject.put("status", deviceAppoint.isStatus() ? 2:1);
			jsonObject.put("status", 2);
			
			JSONArray weekArr=new JSONArray();
			String weekStr=deviceAppoint.getWeek();
			
			if(weekStr.isEmpty()){
				deviceAppoint.setRepeat(false);//不重复
				boolean nextDay = DateUtil.isBeforeCurrTime(deviceAppoint.getTime());
				int weekName = DateUtil.getWeekType();
				if(nextDay){
					weekName ++;
					if(weekName == 8) weekName = 1;
				}
				weekName --;
				if(weekName <= 0) weekName = 7;
				weekArr.put(weekName+"");
			}else{
				deviceAppoint.setRepeat(true);
				for (int i = 0; i < weekStr.length(); i++) {
					String key = String.valueOf(weekStr.charAt(i));
					weekArr.put(key);
				}
			}
			
			jsonObject.put("repeat", deviceAppoint.isRepeat() ? 2:1);
			jsonObject.put("week", weekArr);
			jsonObject.put("isStart", true);
			
		}catch(JSONException e){
			
			e.printStackTrace();
		}
		return jsonObject.toString();
	}
	
	
	public MessageInfo addApplianceAppointResponse(String jsonString){
		MessageInfo info = new MessageInfo();
		String errCode = null;
		String errMsg = null;
		String AppointId = null;
		try{
			//获取json对象
			JSONObject jsonObj=new JSONObject(jsonString);
			try{
				errCode=jsonObj.getString("errCode");
			}catch(Exception e){
				e.printStackTrace();
				errCode=jsonObj.getString("errorCode");
			}
			try{
				errMsg = jsonObj.getString("errMsg");
			}catch(Exception e){
				e.printStackTrace();
				errMsg=jsonObj.getString("msg");
			}
			JSONObject result = jsonObj.getJSONObject("result");
			AppointId = result.getString("applianceAppointId");
			}catch(JSONException e){
				e.printStackTrace();
			}
		
		info.setErrCode(errCode);
		info.setMsg(errMsg);
		info.setBeanInfo(AppointId);
		
		return info;
	}
	
	/**
	 * 1.2.6.3 1.2.6.4 开启预约
	 * @param userId
	 * @param deviceYuYue
	 * @return
	 */
	public String startApplianceAppointRequest(String applianceAppointId){
		JSONObject jsonObject=new JSONObject();
		try{
			jsonObject.put("applianceAppointId",Long.parseLong(applianceAppointId));
		}catch(JSONException e){
			
			e.printStackTrace();
		}
		return jsonObject.toString();
	}
	
	public MessageInfo startApplianceAppointResponse(String jsonString){
		return getErrCodeInfo(jsonString);
	}
	
	/***
	 * 1.2.6.5 关闭预约
	 * @param userId
	 * @param applianceAppointId
	 * @return
	 */
	public String closeApplianceAppointRequest(String applianceAppointId){
		JSONObject jsonObject=new JSONObject();
		try{
			jsonObject.put("applianceAppointId",Long.parseLong(applianceAppointId));
		}catch(JSONException e){
			
			e.printStackTrace();
		}
		return jsonObject.toString();
	}
	
	public MessageInfo closeApplianceAppointResponse(String jsonString){
		return getErrCodeInfo(jsonString);
	}
	
	
	/**
	 * 获取预约列表
	 * @param userId
	 * @param applianceAppointId
	 * @return
	 */
	public String getApplianceAppointDetailRequest(String applianceId){
		JSONObject jsonObject=new JSONObject();
		long applianceid = Long.parseLong(applianceId);
		try{
			jsonObject.put("applianceId",applianceid);
		}catch(JSONException e){
			
			e.printStackTrace();
		}
		return jsonObject.toString();
	}
	
	public MessageInfo getApplianceAppointDetailResponse(String json, IDateZoomTransformer transformer){
		List<DeviceAppoint> appoints = new ArrayList<DeviceAppoint>();
		MessageInfo info = new MessageInfo();
		try{
			//获取json对象
			JSONObject jsonObj=new JSONObject(json);
			info.setErrCode(jsonObj.getString("errCode"));
			info.setMsg(jsonObj.getString("errMsg"));
			JSONArray result = jsonObj.getJSONArray("result");
			
			for(int i=0;i<result.length();i++){
				DeviceAppoint appoint = new DeviceAppoint();
				appoint.setApplianceAppointId(String.valueOf(result.getJSONObject(i).getInt("id")));
				appoint.setRepeat(result.getJSONObject(i).getInt("repeat") == 2 ? true:false);
				appoint.setStatus(result.getJSONObject(i).getInt("status") == 2 ?true:false);
				appoint.setSwitcher(result.getJSONObject(i).getInt("switcher") == 2?true:false);
				appoint.setTime(transformer.toLocal(result.getJSONObject(i).getString("time")));
				JSONArray weekArr = result.getJSONObject(i).getJSONArray("week");
				StringBuilder sb = new StringBuilder();
				if (appoint.isRepeat()) {
					for (int j = 0; j < weekArr.length(); j++) {
						sb.append(weekArr.get(j));
					}
				}
				appoint.setWeek(sb.toString());
				appoints.add(appoint);
			}
		}catch(JSONException e){
				e.printStackTrace();
			}
		
		info.setBeanInfo(appoints);
		
		return info;
	}
	
	
	private String getWeekData(boolean[] weekDay){
		StringBuffer sb = new StringBuffer();
		String result = sb.toString(); 
		for (int i = 0; i < weekDay.length; i++) {
			boolean isCheck = weekDay[i];
			if(isCheck){
				sb.append("1");
			}else{
				sb.append("0");
			}
		}
		return sb.toString();
	}
	
	
	/**
	 * 1.2.6.3 修改预约
	 * @param userId
	 * @param deviceYuYue
	 * @return
	 */
	public String updateApplianceAppointRequest(DeviceAppoint deviceAppoint, IDateZoomTransformer transformer){
		return getDeviceYuYueJsonUpdate(deviceAppoint, transformer);
	}
	
	public String getDeviceYuYueJsonUpdate(DeviceAppoint deviceAppoint, IDateZoomTransformer transformer){
		JSONObject jsonObject=new JSONObject();
		try{
			jsonObject.put("applianceAppointId", Integer.valueOf(deviceAppoint.getApplianceAppointId()));
			jsonObject.put("time", transformer.toUTC(deviceAppoint.getTime()));
			JSONArray weekArr=new JSONArray();
			String weekStr=deviceAppoint.getWeek();
			
			Log.d("ApplianceStatus","  weekStr = "+weekStr);
			deviceAppoint.setRepeat(true);
			if(weekStr.isEmpty()){
				deviceAppoint.setRepeat(false);//不重复
				boolean nextDay = DateUtil.isBeforeCurrTime(deviceAppoint.getTime());
				int weekName = DateUtil.getWeekType();
				if(nextDay){
					weekName ++;
					if(weekName == 8) weekName = 1;
				}
				weekName --;
				if(weekName <= 0) weekName = 7;
				weekArr.put(weekName+"");
			}else{
				for (int i = 0; i < weekStr.length(); i++) {
					String key = String.valueOf(weekStr.charAt(i));
					weekArr.put(key);
				}
			}
			
			jsonObject.put("repeat", deviceAppoint.isRepeat()?2:1);
			jsonObject.put("week", weekArr);
			jsonObject.put("isStart", true);
			
		}catch(JSONException e){
			
			e.printStackTrace();
		}
		return jsonObject.toString();
	}
	
	/**
	 * 1.2.6.3 修改预约
	 * @param jsonString
	 * @return
	 */
	public MessageInfo updateApplianceAppointResponse(String jsonString){
		return getErrCodeInfo(jsonString);
	}
	
	
	/**
	 * 1.2.6.6 获取预约列表
	 * @param userId
	 * @return
	 */
	public String getApplianceAppointListRequest(int userId){
		return createJsonString(userId);
	}
	
	public String createJsonString(int userId){
		JSONObject json=new JSONObject();
		try{
			json.put("userId", userId);
		}catch(JSONException e){
			e.printStackTrace();
		}
		
		return json.toString();
	}
	
	
	
	
	/****
	 * T1 查询定时推送温度通知
	 */
	public String queryT1Schedule(long applianceId){
		JSONObject json=new JSONObject();
		try{
			json.put("applianceId", applianceId);
		}catch(JSONException e){
			e.printStackTrace();
		}
		
		return json.toString();
	}
	
	/**
	 * 曾加定时推送室内温度通知
	 */
	public String addT1Schedule(String applianceId, String time, String week, int repeat, IDateZoomTransformer transformer){
		JSONObject json=new JSONObject();
		long applianceid = Long.parseLong(applianceId);
		try{
			json.put("applianceId", applianceid);
			json.put("time", transformer.toUTC(time));
			json.put("repeat", repeat);
			JSONArray weekArr = new JSONArray();
			for(int i=0;i<week.length();i++){
				weekArr.put(week.charAt(i)+"");
//				if((week.charAt(i)+"").equals("1")){
//					weekArr.put(i+1);
//				}else{
//					weekArr.put(0);
//				}
			}
			json.put("week", weekArr);
		}catch(JSONException e){
			e.printStackTrace();
		}
		
		return json.toString();
	}
	
	/**
	 * 更新T1推送
	 * @param applianceId
	 * @param time
	 * @param week
	 * @param repeat
	 * @return
	 */
	public String updateT1Schedule(long applianceId, String time, String week, int repeat, IDateZoomTransformer transformer){
		JSONObject json=new JSONObject();
		try{
			json.put("applianceId", applianceId);
			json.put("time", transformer.toUTC(time));
			json.put("repeat", repeat);
			JSONArray weekArr = new JSONArray();
			for(int i=0;i<week.length();i++){
				weekArr.put(week.charAt(i));
//				if((week.charAt(i)+"").equals("1")){
//					weekArr.put(i+1);
//				}else{
//					weekArr.put(0);
//				}
			}
			json.put("week", weekArr);
		}catch(JSONException e){
			e.printStackTrace();
		}
		
		return json.toString();
	}
	
	
	public String decodeReturnData(String json, SecurityHandle builder, String accessToken){
		String errorCode;
		String errMsg;
		String returnData = "";
		try{
			//获取json对象
			JSONObject jsonObj=new JSONObject(json);
			errorCode=jsonObj.getString("errorCode");
			if(!errorCode.equals("0")){
				errMsg = jsonObj.getString("msg");
			}
			JSONObject result = jsonObj.getJSONObject("result");
			returnData = result.getString("returnData");
			returnData = builder.Decrypt(returnData, BaseAPI.appKey, accessToken);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return returnData;
		
	}
	
	
	
	public MessageInfo queryT1(String json){
		MessageInfo info = new MessageInfo();
		int errCode = 0;
		String errMsg = "";
		boolean mResult = false;
		try{
			JSONObject jsonObj = new JSONObject(json);
			errCode = jsonObj.getInt("errCode");
			errMsg = jsonObj.getString("errMsg");
			JSONObject result = jsonObj.getJSONObject("result");
			JSONArray weeks = result.getJSONArray("week");
			if(weeks.length() > 0){
				mResult = true;
			}else{
				mResult = false;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		info.setBeanInfo(mResult);
		info.setErrCode(String.valueOf(errCode));
		info.setMsg(errMsg);
		return info;
	}
	
	/**
	 * 解析AppUpdate
	 * @param json
	 * @return
	 */
	public MessageInfo App_updateResponse(String json){
		MessageInfo info = new MessageInfo();
		int errCode = 0;
		String errMsg = "";
		AppInfo appInfo = new AppInfo();
		
		try{
			
			JSONObject jsonObj = new JSONObject(json);
			errCode = jsonObj.getInt("errorCode");
			if(errCode != 0){
				try{
					errMsg = jsonObj.getString("errMsg");
				}catch(JSONException E){
					E.printStackTrace();
					errMsg = jsonObj.getString("msg");
				}
			}
			JSONObject result = jsonObj.getJSONObject("result");
			String versionCode = result.getString("versionCode");
			String appType = result.getString("appType");
			String versionName = result.getString("versionName");
			String des = result.getString("des");
			String size = result.getString("packageSize");
			String uploadTime = result.getString("uploadTime");
			String url = result.getString("url");
			
			appInfo.setVersionCode(versionCode);
			appInfo.setVersionName(versionName);
			appInfo.setUpdateTime(uploadTime);
			appInfo.setDes(des);
			appInfo.setDownloadURL(url);
			appInfo.setSize(size);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		info.setBeanInfo(appInfo);
		info.setErrCode(String.valueOf(errCode));
		info.setMsg(errMsg);
		return info;
	}
	
	/**
	 * 获取更新列表
	 * @param json
	 * @return
	 */
	public MessageInfo Checkforupdate(String json){
		MessageInfo info = new MessageInfo();
		int errCode = 0;
		String errMsg = "";
		List<VersionInfo> infos = new ArrayList<VersionInfo>();
		try{
			JSONObject jsonObj = new JSONObject(json);
			
			errCode = jsonObj.getInt("errorCode");
			if(errCode != 0){
				try{
					errMsg = jsonObj.getString("errMsg");
				}catch(JSONException e){
					errMsg = jsonObj.getString("msg");
					e.printStackTrace();
				}
			}

			JSONObject result = jsonObj.getJSONObject("result");

			JSONArray list = result.getJSONArray("list");
			
			for (int i=0;i<list.length();i++){
				VersionInfo version = new VersionInfo();
				version.setAppType(list.getJSONObject(i).getString("appType"));
				version.setVersionCode(list.getJSONObject(i).getString("versionCode"));
				infos.add(version);
			}
		
		}catch(Exception e){
			e.printStackTrace();
		}
		info.setBeanInfo(infos);
		info.setErrCode(String.valueOf(errCode));
		info.setMsg(errMsg);
		return info;
	}
	
	/**
	 * 解析头像上传接口
	 * @param jsonStr
	 * @return
	 */
	public MessageInfo getProfileURL(String jsonStr){
		MessageInfo info = new MessageInfo();
		String errCode = "0";
		String errMsg = "";
		String profileURL = "";
		
		try{
			JSONObject jsonObj = new JSONObject(jsonStr);
			errCode = jsonObj.getString("errorCode");
			if(errCode.equals("0")){
				JSONObject result = jsonObj.getJSONObject("result");
				profileURL = result.getString("profilePicUrl");
				info.setBeanInfo(profileURL);
			}else{
				try{
					errMsg = jsonObj.getString("errMsg");
				}catch(JSONException e){
					errMsg = jsonObj.getString("msg");
					e.printStackTrace();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		info.setErrCode(errCode);
		info.setMsg(errMsg);
		return info;
		
	}
	
}













